import 'package:ati_package/pages/common/ati_scaffold.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';

import '../../../../core/routes/app_routes.dart';
import '../../../../core/utils/ati_assets.dart';
import '../../../../core/utils/ati_color.dart';
import '../../sign/widgets/sign_hot_exchange.dart';

class PointsMallView extends StatefulWidget {
  const PointsMallView({super.key});

  @override
  State<PointsMallView> createState() => _MyWidgetState();
}

class _MyWidgetState extends State<PointsMallView>
    with SingleTickerProviderStateMixin {
  TabController? tabController; // safer: allow null briefly
  final List<String> tabs = ['热门兑换', '精选好物', '虚拟商品'];

  @override
  void initState() {
    super.initState();
    // 初始化 TabController（放在 initState 中正常创建）
    tabController = TabController(length: tabs.length, vsync: this);
  }

  @override
  void dispose() {
    tabController?.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    // Ensure ScreenUtil 已初始化（如果你的 app 有在主入口初始化则可以忽略）

    return AtiScaffold(
      extendBodyBehindAppBar: true,
      barBgColor: Colors.transparent,
      title: '积分商城',
      body: Stack(
        children: [
          buildBgImage(),
          SafeArea(
            bottom: false,
            child: NestedScrollView(
              // ★ 关键参数：保证内部滚动与外部联动
              floatHeaderSlivers: false,
              headerSliverBuilder: (context, innerBoxIsScrolled) {
                return [
                  SliverToBoxAdapter(child: buildMypoints()),
                  SliverPersistentHeader(
                    pinned: true,
                    delegate: SliverTabBarDelegate(
                      child: PreferredSize(
                        preferredSize: const Size.fromHeight(48),
                        child: buildTabBar(),
                      ),
                    ),
                  ),
                ];
              },
              // ★ 注意：每个 tab 内容要有唯一 Key
              body: TabBarView(
                controller: tabController,
                children: List.generate(tabs.length, (index) {
                  return Builder(
                    builder: (context) {
                      return CustomScrollView(
                        // 为每个 tab 建立独立的滚动容器
                        key: PageStorageKey<String>(tabs[index]),
                        slivers: [
                          SliverPadding(
                            padding: EdgeInsets.all(16.r),
                            sliver: SliverGrid(
                              delegate: SliverChildBuilderDelegate(
                                (context, i) => ProductCard(),
                                childCount: 20,
                              ),
                              gridDelegate:
                                  SliverGridDelegateWithFixedCrossAxisCount(
                                    crossAxisCount: 2,
                                    crossAxisSpacing: 12.5.r,
                                    mainAxisSpacing: 12.r,
                                    childAspectRatio: 0.71,
                                  ),
                            ),
                          ),
                        ],
                      );
                    },
                  );
                }),
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget buildBgImage() {
    return Container(
      height: 250.r,
      width: Get.width,
      decoration: BoxDecoration(
        image: DecorationImage(
          image: AssetImage(AtiAssets.pointsMallBg, package: 'ati_package'),
          fit: BoxFit.fitWidth,
        ),
      ),
    );
  }

  // ---- 保留旧实现（未用到 buildContent） ----
  Widget buildContent() {
    return SafeArea(
      bottom: false,
      child: SingleChildScrollView(
        child: Column(children: [buildMypoints(), buildTabBarList()]),
      ),
    );
  }

  //我的积分
  Widget buildMypoints() {
    return Container(
      padding: EdgeInsets.only(top: 12.5.w, left: 16.r, bottom: 12.5.r),
      decoration: BoxDecoration(borderRadius: BorderRadius.circular(0.r)),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                '我的积分',
                style: TextStyle(
                  fontSize: 12.sp,
                  color: AtiColor.textColor1,
                  fontWeight: FontWeight.w500,
                ),
              ),
              SizedBox(height: 5.h),
              Text(
                '29166',
                style: TextStyle(
                  fontSize: 25.sp,
                  color: AtiColor.successColor,
                  fontWeight: FontWeight.w600,
                ),
              ),
              Text(
                '50积分 = 1USDT',
                style: TextStyle(
                  fontSize: 10.sp,
                  color: const Color(0xFF666666),
                  fontWeight: FontWeight.w500,
                ),
              ),
            ],
          ),
          const Spacer(),
          IncomeExpenseTab(),
        ],
      ),
    );
  }

  Widget buildTabBar() {
    // 包一层 Material，以便 TabBar 的内部渲染（例如水波效果）更稳定
    return Material(
      color: Colors.transparent,
      child: Container(
        margin: EdgeInsets.symmetric(horizontal: 16.r),
        padding: const EdgeInsets.symmetric(horizontal: 8),
        decoration: BoxDecoration(
          gradient: AtiColor.primaryGradient,
          borderRadius: BorderRadius.circular(10.r),
        ),
        child: TabBar(
          controller: tabController,
          // 你之前的样式保留
          indicator: UnderlineTabIndicator(
            borderSide: BorderSide(width: 2.5.r, color: Colors.white),
            insets: EdgeInsets.fromLTRB(16.r, 0, 16.r, 6.r),
          ),
          indicatorSize: TabBarIndicatorSize.label,
          labelColor: Colors.white,
          unselectedLabelColor: Colors.white.withOpacity(0.7),
          labelStyle: const TextStyle(
            fontSize: 16,
            fontWeight: FontWeight.bold,
          ),
          unselectedLabelStyle: const TextStyle(
            fontSize: 16,
            fontWeight: FontWeight.normal,
          ),
          tabs: tabs.map((title) => Tab(text: title)).toList(),
        ),
      ),
    );
  }

  Widget buildTabBarList() {
    return Container(
      margin: EdgeInsets.only(bottom: 35.r),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          Container(
            margin: EdgeInsets.symmetric(horizontal: 16.r),
            padding: const EdgeInsets.symmetric(horizontal: 8),
            decoration: BoxDecoration(
              gradient: AtiColor.primaryGradient,
              borderRadius: BorderRadius.circular(10.r),
            ),
            child: TabBar(
              controller: tabController,
              indicator: UnderlineTabIndicator(
                borderSide: BorderSide(width: 2.5.r, color: Colors.white),
                insets: EdgeInsets.fromLTRB(16.r, 0, 16.r, 6.r),
              ),
              indicatorSize: TabBarIndicatorSize.label,
              labelColor: Colors.white,
              unselectedLabelColor: Colors.white.withOpacity(0.7),
              labelStyle: const TextStyle(
                fontSize: 16,
                fontWeight: FontWeight.bold,
              ),
              unselectedLabelStyle: const TextStyle(
                fontSize: 16,
                fontWeight: FontWeight.normal,
              ),
              tabs: tabs.map((title) {
                return Tab(text: title);
              }).toList(),
            ),
          ),
          // 兼容旧逻辑（若仍想使用）
          SizedBox(
            height: 400.r,
            child: TabBarView(
              controller: tabController,
              children: tabs.map((e) => SignHotExchangeWidget()).toList(),
            ),
          ),
        ],
      ),
    );
  }
}

//按键条
class IncomeExpenseTab extends StatefulWidget {
  const IncomeExpenseTab({super.key});

  @override
  State<IncomeExpenseTab> createState() => _IncomeExpenseTabState();
}

class _IncomeExpenseTabState extends State<IncomeExpenseTab> {
  int _selectedIndex = 0; // 0 收入，1 支出
  final List<String> _tabs = ['积分订单', '积分明细'];

  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: List.generate(_tabs.length, (index) {
        final bool isSelected = _selectedIndex == index;
        return GestureDetector(
          onTap: () {
            setState(() {
              _selectedIndex = index;
            });
            if (_selectedIndex == 0) {
            } else {
              Get.toNamed(AtiAppRoutes.pointsDet);
            }
          },
          child: AnimatedContainer(
            duration: const Duration(milliseconds: 200),
            margin: EdgeInsets.only(right: 16.r, bottom: index == 0 ? 8.r : 0),
            padding: EdgeInsets.symmetric(horizontal: 20.w, vertical: 2.5.h),
            decoration: BoxDecoration(
              color: isSelected ? const Color(0xFF059B4F) : Colors.white,
              borderRadius: BorderRadius.circular(24.r),
              border: Border.all(
                color: isSelected
                    ? const Color(0xFF059B4F)
                    : Colors.grey.shade300,
                width: 1,
              ),
            ),
            child: Text(
              _tabs[index],
              style: TextStyle(
                color: isSelected ? Colors.white : Colors.black,
                fontWeight: FontWeight.w500,
                fontSize: 15.sp,
              ),
            ),
          ),
        );
      }),
    );
  }
}

class SliverTabBarDelegate extends SliverPersistentHeaderDelegate {
  final PreferredSizeWidget child;

  SliverTabBarDelegate({required this.child});

  @override
  double get minExtent => child.preferredSize.height;
  @override
  double get maxExtent => child.preferredSize.height;

  @override
  Widget build(
    BuildContext context,
    double shrinkOffset,
    bool overlapsContent,
  ) {
    return Container(color: Colors.transparent, child: child);
  }

  @override
  bool shouldRebuild(SliverTabBarDelegate oldDelegate) =>
      oldDelegate.child != child;
}

class ProductCard extends StatelessWidget {
  const ProductCard({super.key});

  @override
  Widget build(BuildContext context) {
    return _buildProductCard();
  }

  Widget _buildProductCard() {
    return Container(
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.05),
            blurRadius: 6,
            offset: const Offset(0, 3),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          /// 图片部分（Image.asset 参数顺序修正）
          ClipRRect(
            borderRadius: const BorderRadius.vertical(top: Radius.circular(12)),
            child: AspectRatio(
              aspectRatio: 1.0,
              child: Image.asset(
                'assets/images/find/news_list_m.png',
                package: 'ati_package',
                height: 100.r,
                // fit: BoxFit.cover,
              ),
            ),
          ),

          /// 文字部分
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 6),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  '无纺布外卖餐饮奶茶咖啡',
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(
                    fontSize: 15.sp,
                    fontWeight: FontWeight.w500,
                  ),
                ),
                const SizedBox(height: 6),
                Text.rich(
                  TextSpan(
                    children: [
                      TextSpan(
                        text: '23480积分',
                        style: const TextStyle(
                          color: Colors.green,
                          fontWeight: FontWeight.bold,
                          fontSize: 15,
                        ),
                      ),
                      const TextSpan(
                        text: " 积分",
                        style: TextStyle(color: Colors.green, fontSize: 13),
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
}
